package com.example.dell.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;


import com.example.dell.basic.AppComplication;

import java.io.File;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 工具类：
 */
public class Utils {
    public static void removeItemFromList(Object object, List list) {
        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            if (obj.equals(object)) {
                iter.remove();
            }
        }
    }

    /**
     * 验证手机号：
     *
     * @param phone 手机号；
     * @return 是手机号返回true 否则返回false;
     */
    public static boolean isPhone(String phone) {
        boolean flag = false;
        if (phone == null || TextUtils.isEmpty(phone)) {
            return flag;
        }
        String regExp = "^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\\d{8})$";
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(phone);
        flag = matcher.find();
        return flag;
    }

    public static boolean isMobileNO(String mobileNums) {
        /**
         * 判断字符串是否符合手机号码格式
         * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
         * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
         * 电信号段: 133,149,153,170,173,177,180,181,189
         * @param str
         * @return 待检测的字符串
         */
        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    /**
     * 生成UUID字符串:
     *
     * @return
     */
    public static String getUUIDStr() {
        return UUID.randomUUID().toString();
    }

    /**
     * 验证密码：
     * 以字母开头，后面可以是大小写字母，数字，下划线；长度：6-20位；
     */
    public static boolean isPassword(String password) {
        boolean flag = false;
        if (password == null || TextUtils.isEmpty(password)) {
            return flag;
        }
        //String regExp = "^[a-zA-Z]{1}([a-zA-Z0-9]|[_]){5,14}$";
        String regExp = "^([a-zA-Z0-9]){6,20}$";
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(password);
        flag = matcher.find();
        return flag;
    }

    /**
     * 获取该应用的版本号：
     */
    public static int getVersionCode() {
        PackageInfo info = getPackageInfo();
        return info.versionCode;
    }

    /**
     * 获取该应用版本名：
     *
     * @return
     */
    public static String getVersionName() {
        PackageInfo info = getPackageInfo();
        return info.versionName;
    }

    /**
     * 获取该应用的包信息：
     *
     * @return
     */
    @Nullable
    private static PackageInfo getPackageInfo() {
        PackageManager manager;
        PackageInfo info = null;
        manager = AppComplication.mContext.getPackageManager();
        try {
            info = manager.getPackageInfo(AppComplication.mContext.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 解决 InputMethodManager.sInstance内存泄漏为题；
     * 在Activity.onDestroy（）后调该方法；
     *
     * @param destContext
     */
    public static void fixInputMethodManagerLeak(Context destContext) {
        try {
            if (destContext == null) {
                return;
            }
            InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm == null) {
                return;
            }
            String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
            Field f = null;
            Object obj_get = null;
            for (int i = 0; i < arr.length; i++) {
                String param = arr[i];
                try {
                    f = imm.getClass().getDeclaredField(param);
                    if (f.isAccessible() == false) {
                        f.setAccessible(true);
                    } // author: sodino mail:sodino@qq.com
                    obj_get = f.get(imm);
                    if (obj_get != null && obj_get instanceof View) {
                        View v_get = (View) obj_get;
                        if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                            f.set(imm, null); // 置空，破坏掉path to gc节点
                        } else {
                            break;
                        }
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        } catch (Exception e) {
        }
    }

    public static String md5Encode(String inStr) throws Exception {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    //android获取一个用于打开Word文件的intent
    public static Intent getWordFileIntent(Context mContext, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addCategory("android.intent.category.DEFAULT");
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, "application/msword");
        return intent;
    }

    //android获取一个用于打开Excel文件的intent
    public static Intent getExcelFileIntent(Context mContext, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, "application/vnd.ms-excel");
        return intent;
    }

    //android获取一个用于打开PPT文件的intent
    public static Intent getPPTFileIntent(Context mContext, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        return intent;
    }

    //android获取一个用于打开文本文件的intent
    public static Intent getTextFileIntent(Context mContext, String param, boolean paramBoolean) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (paramBoolean) {
            Uri uri;
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", new File(param));
            } else {
                uri = Uri.fromFile(new File(param));
            }
            intent.setDataAndType(uri, "text/plain");
        } else {
            Uri uri;
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", new File(param));
            } else {
                uri = Uri.fromFile(new File(param));
            }
            intent.setDataAndType(uri, "text/plain");
        }
        return intent;
    }

    //android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(Context mContext, String param) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", new File(param));
        } else {
            uri = Uri.fromFile(new File(param));
        }
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }

    //android获取一个用于打开jpng文件的intent
    public static Intent getJpgFileIntent(Context mContext, String param) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", new File(param));
        } else {
            uri = Uri.fromFile(new File(param));
        }
        intent.setDataAndType(uri, "image/jpeg");
        return intent;
    }
    //android获取一个用于打开Zip文件的intent
    public static Intent getZipFileIntent(Context mContext, String param) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", new File(param));
        } else {
            uri = Uri.fromFile(new File(param));
        }
        intent.setDataAndType(uri, "application/zip");
        return intent;
    }
    //android获取一个用于打开Rar文件的intent
    public static Intent getRarFileIntent(Context mContext, String param) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext, "com.lwgk.fileprovider", new File(param));
        } else {
            uri = Uri.fromFile(new File(param));
        }
        intent.setDataAndType(uri, "application/x-rar-compressed");
        return intent;
    }
}
